package edu.mju.controller;

import edu.mju.entity.User;
import edu.mju.service.IUserService;
import edu.mju.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * @Author:wyp
 * @Date:2020/5/9 12:00
 */
@WebServlet("/register")
public class RegisterController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/view/register.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String loginName=req.getParameter("userName");
        String loginPwd=req.getParameter("passWord");
        String capche = req.getParameter("inputCapche");
        String tel = req.getParameter("telphone");
        Byte sex = Byte.valueOf(req.getParameter("sex"));
        User inuser = new User(loginName,loginPwd,tel,sex,"tourist");
        //获取生成的验证码
        String capCode = (String) req.getSession().getAttribute("capcode");
        String str;

        //如果用户名是学号，密码是1234，正确显示你好，如果错误，显示账号或密码错误
        if(capCode != null) {
            if (capCode.equals(capche)) {
                IUserService userService = new UserServiceImpl();
                boolean reuser = userService.save(inuser);
                if(reuser){
                    resp.setContentType("text/html;charSet=GBK");
                    PrintWriter out = resp.getWriter();
                    out.print("<script>alert('注册成功，请登录！'); window.location='./login' </script>");
                    out.flush();
                    out.close();
                }else {
                    registerFail(req,resp,"注册失败");
                }
            }else {
                registerFail(req,resp,"验证码错误");
            }
        }else {
            registerFail(req,resp,"验证码未生成");
        }
    }

    private void registerFail(HttpServletRequest req,HttpServletResponse resp,String str) throws ServletException, IOException {
        resp.setContentType("text/html;charSet=GBK");
        PrintWriter out = resp.getWriter();
        out.print("<script>alert('"+str+"'); window.location='./register' </script>");
        out.flush();
        out.close();
    }
}
